package com.example.uniapp.activity.main;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.uniapp.R;
import com.example.uniapp.dao.UserDao;
import com.example.uniapp.db.DBUtils;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //数据库初始化
        DBUtils dbUtils = new DBUtils(this);
        DBUtils.con = dbUtils.getWritableDatabase();

        //实现数据共享
        SharedPreferences sharedPreferences = getSharedPreferences("data", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        //点击注册按钮后的操作
        Button registerButton = findViewById(R.id.login_register);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转到注册界面
                Intent intent=new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        //点击登录按钮后的操作
        Button loginButton = findViewById(R.id.login_login);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取账号密码
                EditText accountText = findViewById(R.id.login_account);
                String account = accountText.getText().toString();
                EditText pwdText = findViewById(R.id.login_pwd);
                String pwd = pwdText.getText().toString();

                //判断账号密码是否为空
                if(account.isEmpty()) {
                    Toast.makeText(MainActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
                }else if(pwd.isEmpty()) {
                    Toast.makeText(MainActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                }else {
                    //判断密码是否输入正确
                    int result = UserDao.login(account, pwd);
                    if(result == 1) {
                        //存数据
                        editor.putString("account", account);
                        editor.apply();
                        Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                        //登录成功则跳转到软件主界面中
                        Intent intent=new Intent(MainActivity.this, MainUserActivity.class);
                        startActivity(intent);
                    }else {
                        Toast.makeText(MainActivity.this, "账号或密码输入错误", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }
}